// import {notification} from 'antd';
import axios from "axios";
import Cookie from "@/utils/cookie";
import {history} from "@@/core/history";
import { message } from 'antd/lib/index';

//重复的请求手动中断
const pendingRequests = new Map();

const cancelPendingRequests = (config,cancel) => {
  const url = config.url;
  const method = config.method;
  const key = `${method}-${url}`;
  if (pendingRequests.has(key)) {
    const cancelToken = pendingRequests.get(key);
    cancelToken();
  }
  pendingRequests.set(key, cancel);
};
const  stopRequest =async ()=>{
  pendingRequests.forEach((cancelToken, key) => {
    cancelToken(); // 调用取消函数
  });
  // 清空 pendingRequests Map
  pendingRequests.clear();
  return  true
}
/** 异常处理程序 */
const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌过期、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务器繁忙，请稍后重试',
  504: '接口连接超时，请重试',
};
const requestError = {
  ECONNABORTED:"请求被中断",
  ECONNREFUSED:"请求被拒绝",
  ENOTFOUND:"域名未找到",
  EAI_AGAIN:"DNS查询失败",
  ERR_BAD_REQUEST:"请求错误,请求参数不正确",
  ERR_NETWORK:"网络不通或接口地址不正确",
  ERR_CANCELED:"请求取消",
}
const errorHandler = error => {
  // console.log(error,"eeee");
  if(axios.isCancel(error)){
    console.log("Request cancelled",error.message);
    return null;
  }
  const { response } = error;
  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    const { status } = response;
/*    notification.error({
      message: `请求错误 ${status}`,
      description: errorText,
    });*/
  } else if (!response) {
    const text = requestError[error.code] || error.message;
/*      notification.info({
        description: text,
        message: '提示',
      });*/
  }
  if(error?.response?.status===401||error?.response?.status===403){
    history.push({
      pathname: '/login',
    });
  }
  return undefined;
};
const retryConnect = (obj) => {
  let config = obj.config; // 获取错误信息
  if (!config || !config.retry) return Promise.reject(obj);
  config.__retryCount = config.__retryCount || 0;
  if (config.__retryCount >= config.retry) {
    return Promise.reject(obj);
  }
  // 重试次数记录
  config.__retryCount += 1;
  let retryPromise = new Promise(function (resolve) {
    setTimeout(function () {
      resolve();
    }, config.retryDelay || 1);
  });
  // Return the promise in which recalls axios to retry the request
  return retryPromise.then(function () {
    return request(config);
  });
};
let loaddingNumber = 0; // 记录请求次数
//对 extend 实例进行简单的封装
const request = axios.create({
  timeout: 1000 * 360, // 超时时间
  headers: {
    // headers中搭载token等请求头信息
    'Content-Type': 'application/json;charset=UTF-8',
  },
  //处理请求错误 调用上面的错误处理逻辑
  errorHandler: errorHandler,
});
request.defaults.retry = 2;
request.defaults.retryDelay = 1000; // 全局的请求的间隙
// 对实例request进行请求拦截
// 可以在里面对url、option中的参数进行进一步处理
request.interceptors.request.use((config) => {
  loaddingNumber++;
  config.cancelToken=new axios.CancelToken((cancel)=>{
    cancelPendingRequests(config,cancel)
  })
  config.headers['Accept'] = '*/*';
  const searchParams = new URLSearchParams(window.location.search);
  const params = {};
  for (const [key, value] of searchParams.entries()) {
    params[key] = value;
  }
  let token = params.token ?? Cookie.get('token')
  if(window.location.pathname!=='/login'
    && !config.url.includes('hotQues')
    && !config.url.includes('oneClickLogin')
    && !token
  ) {
/*    notification.info({
      message: "登录已过期或未登录",
    });*/
    return history.push({
      pathname: '/login',
    });
  }else {
    if (config?.data instanceof FormData) {
      config.data.append("token", token);
      config.headers["Content-Type"] = "multipart/form-data; charset=UTF-8";
    }
      config.headers.token = token;
      config.headers["X-Access-Token"] = token;
    if (config.method.toUpperCase() === 'POST') {
      if (config?.data instanceof FormData) {
        delete config.headers["Content-Type"];
      }
    }
  }
  return config;
});

// 对实例request进行响应拦截, 统一处理接口错误信息
request.interceptors.response.use(async response => {
  loaddingNumber--;
    console.log(response,"rrrrrr")
    // 移除已完成的请求
    const key = `${response.config.method}-${response.config.url}`;
    pendingRequests.delete(key);
    if (response.data instanceof Blob) {
      if(response.status!==200){
/*        notification.warn({
          message: codeMessage[response.status],
        });*/
      }
      let fileName = "";
      if (response?.headers["content-disposition"]) {
        let headersText = response.headers["content-disposition"].split(";");
        let name =
          (headersText.length > 0 && headersText[1].split("=")[1]) || false;
        fileName = name && decodeURIComponent(name);
      }
      return {
        fileData: response.data,
        fileName,
      }
    } else {
      if(response?.data?.code!==200&&response?.data?.code!==0){
        switch (response?.data?.code) {
          case 401:
            if(Cookie.get('token')) Cookie.del('token');
        /*    notification.info({
              message: codeMessage[response.data?.code],
            });*/
            history.push({
              pathname: '/login',
            });
            break;
          case 403:
            if(Cookie.get('token')) Cookie.del('token');
         /*   notification.info({
              message: codeMessage[response.data?.code],
            });*/
            history.push({
              pathname: '/login',
            });
            break;
        }
      }
      return response.data
    }
},error => {
    loaddingNumber--;
    let status = error&&error?.status||0;
    let count = error&&error?.config?.__retryCount||0
    if(count===2){
      if(status===404) {
        message.info("请求地址不存在，请核对",2)
      }else if(status===504) {
        message.info("响应超时，请重试",2)
      }else if(status===500) {
        message.info("配置错误，服务器处理失败",2)
      }
    }
    // 如果响应是错误的，调用 errorHandler 处理错误
    errorHandler(error);
  // 抛出错误，以便在请求的地方进行进一步处理（例如，使用 try...catch 语句）
  // return Promise.reject(error);
    console.log(error,"eeeee")
    return retryConnect(error);
}
);
export {request,stopRequest};
